<!-- 入住登记 -->
<template>
  <el-form :model="userInfo">
    <!-- 基本信息 -->
    <div class="card">
      <el-card style="max-width: 80vw">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <div class="card-body">
          <el-form-item label="姓名">
            <el-input v-model="userInfo.baseInfo.name" />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="userInfo.baseInfo.gender" placeholder="请选择">
              <el-option value="男">男</el-option>
              <el-option value="女">女</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker v-model="userInfo.baseInfo.birthDate" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择" clearable />
          </el-form-item>
          <el-form-item label="婚姻">
            <el-select v-model="userInfo.baseInfo.maritalStatus" placeholder="请选择">
              <el-option value="已婚">已婚</el-option>
              <el-option value="单身">单身</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="户籍地">
            <el-input v-model="userInfo.baseInfo.domicile" />
          </el-form-item>
          <el-form-item label="民族">
            <el-input v-model="userInfo.baseInfo.nation" />
          </el-form-item>
          <el-form-item label="身份证">
            <el-input v-model="userInfo.baseInfo.idCard" />
          </el-form-item>
          <el-form-item label="身高">
            <el-input v-model="userInfo.baseInfo.height">
              <template #append>cm</template>
            </el-input>
          </el-form-item>
          <el-form-item label="体重">
            <el-input v-model="userInfo.baseInfo.weight">
              <template #append>kg</template>
            </el-input>
          </el-form-item>
        </div>
      </el-card>
    </div>
    <!-- 家属信息 -->
    <div class="card">
      <el-card style="max-width: 80vw">
        <template #header>
          <div class="card-header">
            <span>家属信息</span>
          </div>
        </template>
        <div class="card-body">
          <el-form v-for="(member, index) in userInfo.familyMembers" :key="index" :model="member" label-width="auto"
            style="max-width: 60vw" class="family-member">
            <el-form-item label="姓名">
              <el-input v-model="member.name" />
            </el-form-item>
            <el-form-item label="与老人关系">
              <el-input v-model="member.relationship"> </el-input>
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="member.phone"> </el-input>
            </el-form-item>
            <!-- <el-button type="danger" @click="removeFamilyMember(index)">删除此行</el-button> -->
          </el-form>

          <!-- <el-button type="primary" @click="addFamilyMember" class="addButton">添加家属</el-button> -->
        </div>
      </el-card>
    </div>
    <!-- 健康信息 -->
    <div class="card">
      <el-card style="max-width: 80vw">
        <template #header>
          <div class="card-header">
            <span>健康信息</span>
          </div>
        </template>
        <div class="card-body">
          <el-form-item label="疾病史">
            <el-input v-model="userInfo.healthInfo.diseaseHistory" />
          </el-form-item>
          <el-form-item label="目前健康状态">
            <el-input v-model="userInfo.healthInfo.healthStatus" />
          </el-form-item>
        </div>
      </el-card>
    </div>
    <!-- 入院信息 -->
    <div class="card">
      <el-card style="max-width: 80vw">
        <template #header>
          <div class="card-header">
            <span>入院信息</span>
          </div>
        </template>
        <div class="card-body">
          <el-form-item label="入院时间">
            <el-date-picker v-model="userInfo.admissionInfo.admissionTime" value-format="YYYY-MM-DD" placeholder="请选择"
              clearable />
          </el-form-item>
          <el-form-item label="住处分配">
            <el-select v-model="userInfo.admissionInfo.buildingNo" placeholder="选择单元楼" style="width: 15vw">
              <el-option v-for="item in buildingOptions" :key="item.value" :value="item.value" />
            </el-select>
            <el-select v-model="userInfo.admissionInfo.floorNo" placeholder="选择楼层数" style="width: 15vw">
              <el-option v-for="item in floorOptions" :key="item.value" :value="item.value" />
            </el-select>
            <el-select v-model="userInfo.admissionInfo.roomNo" placeholder="选择房间号" style="width: 15vw">
              <el-option v-for="item in roomOptions" :key="item.value" :value="item.value" />
            </el-select>
            <el-select v-model="userInfo.admissionInfo.bedNo" placeholder="选择床位号" style="width: 15vw">
              <el-option v-for="item in bedOptions" :key="item.value" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
      </el-card>
    </div>
    <!-- 提交/重置按钮 -->
    <div class="finalBtn">
      <el-form-item>
        <el-button type="primary" @click="commitInfo"> 提交 </el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, onMounted,computed, } from "vue";
import type { UserInfo, BaseInfo, FamilyInfo, BedInfo } from "@/API/interface/checkInUpdate"
import { checkInElderApi } from "@/API/interface/checkInUpdate"
import { getAllBeds } from '@/API/interface/bedManagement'
import { ElMessage } from 'element-plus'
const userInfo = ref<UserInfo>({
  baseInfo: {
    //基本信息
    name: "",
    gender: "",
    birthDate: new Date(), //出生日期
    domicile: "", //户籍地
    idCard: "", //身份证号
    height: "", //身高
    weight: "", //体重
    nation: "", //民族
    maritalStatus: "", //婚姻状况
  }, //基本信息
  familyMembers: [
    {
      name: "",
      relationship: "", //与本人关系
      phone: "", //联系电话
    },
  ], //家庭成员信息
  healthInfo: {
    diseaseHistory: "", //疾病史
    healthStatus: "", //目前健康状况
  }, //健康信息
  admissionInfo: {
    admissionTime: new Date(), //入院时间
    buildingNo: "", //单元楼
    floorNo: "", //楼层数
    roomNo: "", //房间号
    bedNo: "", //床位号
  }, //入院信息
});
// 楼房信息
// 一进来页面就发请求获取数据
// onMounted(async () => {
//   const res = await getAllBeds();
//   console.log("获取所有床位", res.data);

//   // 动态填充楼房、楼层、房间和床位信息
//   const uniqueBuildings = new Set<string>();
//   const uniqueFloors = new Set<string>();
//   const uniqueRooms = new Set<string>();
//   const uniqueBeds = new Set<string>();

//   res.data.data.forEach((bed: any) => {
//     uniqueBuildings.add(bed.buildingNo);
//     uniqueFloors.add(bed.floorNo);
//     uniqueRooms.add(bed.roomNo);
//     uniqueBeds.add(bed.bedNo);
//   });

//   cells.value = Array.from(uniqueBuildings).map(building => ({ value: building }));
//   floorValues.value = Array.from(uniqueFloors).map(floor => ({ value: floor }));
//   roomValues.value = Array.from(uniqueRooms).map(room => ({ value: room }));
//   bedValues.value = Array.from(uniqueBeds).map(bed => ({ value: bed }));
// });
// const cells = ref([
//   { value: "" },
// ]);
// const floorValues = ref([
//   { value: "" },
// ]);
// const roomValues = ref([
//   { value: "" },
// ]);
// const bedValues = ref([
//   { value: "" },
// ]);
// 添加家属
// const addFamilyMember = () => {
//   userInfo.value.familyMembers.push({
//     name: "",
//     relationship: "",
//     phone: "",
//   });
// };
// 删除家属信息
// const removeFamilyMember = (index: number) => {
//   userInfo.value.familyMembers.splice(index, 1);
// };
// 原始床位数据（从接口获取）
const allBeds = ref<any[]>([])

// 获取所有床位数据
const getAllBed = async () => {
  const res = await getAllBeds() 
  allBeds.value = res.data.data
}

// 初始化加载数据
onMounted(() => {
  getAllBed()
})

// 楼栋选项（始终显示全部）
const buildingOptions = computed(() => {
  const buildings = new Set(allBeds.value.map(b => b.buildingNo))
  return Array.from(buildings).map(b => ({
    value: b,
    label: `${b}栋`
  }))
})

// 楼层选项（根据楼栋筛选）
const floorOptions = computed(() => {
  if (!userInfo.value.admissionInfo.buildingNo) return []
  
  const floors = new Set(
    allBeds.value
      .filter(b => b.buildingNo === userInfo.value.admissionInfo.buildingNo)
      .map(b => b.floorNo)
  )
  return Array.from(floors).map(f => ({
    value: f,
    label: `${f}层`
  }))
})

// 房间选项（根据楼栋+楼层筛选）
const roomOptions = computed(() => {
  if (!userInfo.value.admissionInfo.floorNo) return []
  
  const rooms = new Set(
    allBeds.value
      .filter(b => 
        b.buildingNo === userInfo.value.admissionInfo.buildingNo &&
        b.floorNo === userInfo.value.admissionInfo.floorNo
      )
      .map(b => b.roomNo)
  )
  return Array.from(rooms).map(r => ({
    value: r,
    label: `${r}室`
  }))
})

// 床位选项（根据楼栋+楼层+房间筛选）
const bedOptions = computed(() => {
  if (!userInfo.value.admissionInfo.roomNo) return []
  
  return allBeds.value
    .filter(b => 
      b.buildingNo === userInfo.value.admissionInfo.buildingNo &&
      b.floorNo === userInfo.value.admissionInfo.floorNo &&
      b.roomNo === userInfo.value.admissionInfo.roomNo
    )
    .map(b => ({
      value: b.bedNo,
      label: `${b.bedNo}号床`,
      disabled: b.status === 'occupied' // 可添加床位状态判断
    }))
})
//提交信息
const commitInfo = async () => {
  const baseInfo: BaseInfo = {
    name: userInfo.value.baseInfo.name,
    gender: userInfo.value.baseInfo.gender,
    birthDate: userInfo.value.baseInfo.birthDate,
    domicile: userInfo.value.baseInfo.domicile,
    idCard: userInfo.value.baseInfo.idCard,
    height: userInfo.value.baseInfo.height,
    weight: userInfo.value.baseInfo.weight,
    nation: userInfo.value.baseInfo.nation,
    maritalStatus: userInfo.value.baseInfo.maritalStatus,
    diseaseHistory: userInfo.value.healthInfo.diseaseHistory,
    healthStatus: userInfo.value.healthInfo.healthStatus,
    admissionTime: userInfo.value.admissionInfo.admissionTime,
  }
  const familyMembers = userInfo.value.familyMembers;
  const familyInfo: FamilyInfo[] = [];
  // 遍历 familyMembers 数组
  familyMembers.forEach((member: { name: string; relationship: string; phone: string }) => {
    familyInfo.push({
      name: member.name,
      relationship: member.relationship,
      phone: member.phone,
    });
  });
  const bedInfo: BedInfo = {
    bedNo: userInfo.value.admissionInfo.bedNo,
    buildingNo: userInfo.value.admissionInfo.buildingNo,
    roomNo: userInfo.value.admissionInfo.roomNo,
    floorNo: userInfo.value.admissionInfo.floorNo,
  };
  console.log("基本信息", baseInfo);
  console.log("家庭信息", familyInfo);
  console.log("床位信息", bedInfo);
  const checkInfo: any = {

    baseInfo: baseInfo,
    familyInfo: familyInfo,
    bedInfo: bedInfo,

  };
  const res = await checkInElderApi(checkInfo)
  console.log("入住结果返回", res);
  if (res.data.code === 200) {
    ElMessage.success("入住成功");
    ElMessage({
    showClose: true,
    type: 'success',
    message: "用户编号为："+res.data.data,
    center: true,
    duration:20000
  })
    //清空表单
    userInfo.value = {
      baseInfo: {
        name: "",
        gender: "",
        birthDate: new Date(),
        domicile: "",
        idCard: "",
        height: "",
        weight: "",
        nation: "",
        maritalStatus: "",
      },
      familyMembers: [],
      healthInfo: {
        diseaseHistory: "", //疾病史
        healthStatus: "", //目前健康状况
      }, //健康信息
      admissionInfo: {
        admissionTime: new Date(), //入院时间
        buildingNo: "", //单元楼
        floorNo: "", //楼层数
        roomNo: "", //房间号
        bedNo: "", //床位号
      }, //入院信息
    }
  } else {
    ElMessage.error("入住失败");
  }
}
</script>

<style lang="less" scoped>
.card {
  margin-top: 1vw;

  .card-header {
    font-size: 1.5em;
    font-weight: bold;
    color: #409eff;
  }

  .el-card /deep/ .el-card__header {
    padding: 1vw;
  }

  .card-body {
    //所有子项目的长度限定
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .el-form-item {
      width: 20%;
      margin: 1vh 1vw;
    }

    .family-member {
      display: flex;
      align-items: center;
    }

    .addButton {
      margin-left: -11vw;
    }
  }

  .el-card /deep/ .el-card__body {
    padding: 0.5vw;
  }
}

.finalBtn {
  display: flex;
  margin-left: 35vw;
  margin-top: 1vw;
}
</style>